﻿using HuaweiCloud.Dotnet.Samples.ESports.Common.Messages;
using HuaweiCloud.Dotnet.Samples.ESports.Device.Dto;
using HuaweiCloud.Dotnet.Samples.ESports.Device.Service;
using MassTransit;
using Microsoft.AspNetCore.Mvc;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace HuaweiCloud.Dotnet.Samples.ESports.Device.Controllers
{
    [Route("api-device/v1/[controller]")]
    [Route("api/v1/[controller]")]
    [ApiController]
    public class SportController : ControllerBase
    {
        private readonly ISportService _service;
        private readonly IPublishEndpoint _publishEndpoint;
        public SportController(ISportService service, IPublishEndpoint publishEndpoint)
        {
            _service = service;
            _publishEndpoint = publishEndpoint;
        }
        [HttpGet]
        public async Task<ActionResult<IEnumerable<SportDto>>> Get()
        {
            return Ok(await _service.ListAsync());
        }
        [HttpGet("{id}")]
        public async Task<ActionResult<SportDto>> Get(string id)
        {
            var item = await _service.GetAsync(id);
            return item == null ? NotFound() : Ok(item);
        }

        [HttpGet("withdevice/{id}")]
        public async Task<ActionResult<List<SportDto>>> GetByDevice(string id)
        {
            if (string.IsNullOrEmpty(id)) 
                return NotFound();
            var item = await _service.ListAsync(x => x.DeviceId == id);
            return item == null ? NotFound() : Ok(item);
        }

        [HttpPost]
        public async Task<ActionResult> Post([FromBody] CreateSportDto dto)
        {
            await _service.AddAsync(dto);
            await _publishEndpoint.Publish<UpdateSportInfo>(new
            {
                DeviceId = dto.DeviceId,
                StartTime = dto.StartTime,
                EndTime = dto.EndTime,
                Description = dto.Description,
                Distance = dto.Distance
            });
            return Accepted();
        }
    }
}
